package com.softWang.common.service;

import com.softWang.common.exception.LogicException;
import com.softWang.common.service.email.EmailSimpleRequestDTO;
import com.softWang.common.service.email.EmailTemplateRequestDTO;
import com.softWang.common.utils.StringUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import javax.validation.Valid;
import java.io.File;

/**
 * 邮件服务
 */
@Service
@Validated
public class EmailService {
    @Value("${spring.mail.username}")
    private String from;

    @Resource
    private JavaMailSender mailSender;
    @Resource
    private TemplateEngine templateEngine;


    public void sendSimpleMail(@Valid EmailSimpleRequestDTO emailDto) throws Exception{
        if (emailDto == null) {
            return;
        }
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "utf-8");
        helper.setFrom(from);
        helper.setTo(emailDto.getTo().toArray(new String[0])); // 收件人
        helper.setSubject(emailDto.getSubject()); // 主题

        //通过简单的正则替换获取内容
        String content = StringUtil.replaceTemplateStr(emailDto.getTemplateStr(),emailDto.getParams());
        helper.setText(content, emailDto.isHtml()); // 内容

        if(emailDto.getCc()!= null && emailDto.getCc().size() > 0){
            helper.setCc(emailDto.getCc().toArray(new String[0])); // 抄送人
        }
        if(emailDto.getBcc()!= null && emailDto.getBcc().size() > 0){
            helper.setBcc(emailDto.getBcc().toArray(new String[0])); // 密送人
        }

        // 添加附件
        if (emailDto.getAttachments() != null && emailDto.getAttachments().size() > 0) {
            for (File file : emailDto.getAttachments()) {
                if (!file.exists()) {
                    throw new LogicException("附件不存在:" + file.getAbsolutePath());
                } else {
                    helper.addAttachment(file.getName(), file);
                }
            }
        }

        mailSender.send(message);
    }


    public void sendTemplateMail(@Valid EmailTemplateRequestDTO emailDto) throws Exception{
        if (emailDto == null) {
            return;
        }
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "utf-8");
        helper.setFrom(from);
        helper.setTo(emailDto.getTo().toArray(new String[0])); // 收件人
        helper.setSubject(emailDto.getSubject()); // 主题

        // 使用Thymeleaf渲染模板
        Context context = new Context();
        context.setVariables(emailDto.getParams());
        String htmlContent = templateEngine.process("email/" + emailDto.getTemplateName(), context);

        //设置html内容
        helper.setText(htmlContent, true);

        if(emailDto.getCc()!= null && emailDto.getCc().size() > 0){
            helper.setCc(emailDto.getCc().toArray(new String[0])); // 抄送人
        }
        if(emailDto.getBcc()!= null && emailDto.getBcc().size() > 0){
            helper.setBcc(emailDto.getBcc().toArray(new String[0])); // 密送人
        }

        // 添加附件
        if (emailDto.getAttachments() != null && emailDto.getAttachments().size() > 0) {
            for (File file : emailDto.getAttachments()) {
                if (!file.exists()) {
                    throw new LogicException("附件不存在:" + file.getAbsolutePath());
                } else {
                    helper.addAttachment(file.getName(), file);
                }
            }
        }

        mailSender.send(message);
    }


}
